﻿myApp.controller('ContentUpdaterController', function ($http, $window, $routeParams, $scope, $rootScope, $location, $window, authService, $timeout, $compile, previewService) {
    $scope.isSuccess = false;
    $scope.isWarning = false;

    var toolbarOptions = [
         [{ 'font': [] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
         [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
         [{ 'align': [] }],

         ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
         ['blockquote', 'code-block'],
         ['link', 'image', 'video'],

         [{ 'header': 1 }, { 'header': 2 }],               // custom button values
         [{ 'list': 'ordered' }, { 'list': 'bullet' }],
         [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
         [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
         [{ 'direction': 'rtl' }],                         // text direction
    ];

    function imageHandler() {
        var range = this.quill.getSelection();
        var value = prompt('What is the image URL');
        this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
    }

    var quill = new Quill('#editor', {
        modules: {
            toolbar: {
                container: toolbarOptions,
                handlers: {
                    image: imageHandler
                }
            }
        },
        theme: 'snow'
    });


    $scope.$emit('newPageLoaded', {
        'title': 'Buy / Rent | ShiJie Property',
        'description': "Buy / Rent Property. We Work Very Closely With Developers. Over 40 Years Experience. Buy / Rent Your Property With ShiJie Property Today!",
        'keywords': 'buy property, rent property'
    });
    $scope.blg = {};

    $http.get('/api/Blog/GetBlog?Url=' + $routeParams.name)
           .success(function (data) {
               var data = data[0];
               if (!$window.localStorage.getItem("u_update_existing")) {
                   $scope.blg.url = $routeParams.name;
                   $scope.blg.title = data.title;
                   $scope.blg.metatitle = data.metatitle;
                   $scope.blg.metadescription = data.metadescription;
                   $scope.blg.metakeywords = data.keywords;

                   quill.root.innerHTML = data.contents.replace(/'/g, "\"");
                   $window.localStorage.setItem("u_update_existing", "true");
                   $window.localStorage.setItem("u_url", $scope.blg.url);
                   $window.localStorage.setItem("u_title", $scope.blg.title);
                   $window.localStorage.setItem("u_metatitle", $scope.blg.metatitle);
                   $window.localStorage.setItem("u_metadescription", $scope.blg.metadescription);
                   $window.localStorage.setItem("u_metakeywords", $scope.blg.metakeywords);
                   $window.localStorage.setItem("u_contents", quill.root.innerHTML);
               }
           })
           .error(function (err) {
               $window.location.href = "/";
           });


 

    //$http.get("https://jsonblob.com/api/jsonBlob/59dabf1a-05a5-11e7-a0ba-3d29ef7ce3f8")
    //  .success(function (data) {
    //      // alert(JSON.stringify(data));
    //      if (data.url == $routeParams.name) {
    //          if (!$window.localStorage.getItem("update_existing")) {
    //              $scope.blg.url = $routeParams.name;
    //              $scope.blg.title = data.title;
    //              $scope.blg.metatitle = data.metatitle;
    //              $scope.blg.metadescription = data.metadescription;
    //              $scope.blg.metakeywords = data.keywords;
    //              quill.root.innerHTML = data.contents.replace(/'/g, "\"");
    //              $window.localStorage.setItem("update_existing", "true");
    //              $window.localStorage.setItem("u_url", $scope.blg.url);
    //              $window.localStorage.setItem("u_title", $scope.blg.title);
    //              $window.localStorage.setItem("u_metatitle", $scope.blg.metatitle);
    //              $window.localStorage.setItem("u_metadescription", $scope.blg.metadescription);
    //              $window.localStorage.setItem("u_metakeywords", $scope.blg.metakeywords);
    //              $window.localStorage.setItem("u_contents", quill.root.innerHTML);
    //          }

    //      } else {
    //          //alert("Blog not found!")
    //          $window.location.href = "/";
    //      }
    //  })
    //  .error(function (err) {
    //      alert("ERR: " + JSON.stringify(err));
    //  });
   


    $scope.changeEditor = "Switch to Source Code";
    $scope.isHTMLEdit = false;

    var BASE_URL;
    if ($location.host() == "localhost") {
        BASE_URL = $location.protocol() + "://" + "localhost:" + $location.port();
    } else {
        BASE_URL = $location.protocol() + "://" + $location.host();
    }
    $scope.BASE_URL = BASE_URL;
   

   

    quill.on('editor-change', function (eventName, ...args) {
        if (eventName === 'text-change') {
         //document.getElementById('editorText').value = quill.root.innerHTML;
         $window.localStorage.setItem("u_contents", quill.root.innerHTML);
         $scope.blg.contents = quill.root.innerHTML;
        } 
    });

    $scope.inputChange = function(){
        console.log("INPUT IS CHANGING...");
        $window.localStorage.setItem("u_url", $scope.blg.url);
        $window.localStorage.setItem("u_title", $scope.blg.title);
        $window.localStorage.setItem("u_metatitle", $scope.blg.metatitle);
        $window.localStorage.setItem("u_metadescription", $scope.blg.metadescription);
        $window.localStorage.setItem("u_metakeywords", $scope.blg.metakeywords);
    }

    $scope.htmlEditorChange = function () {
        $window.localStorage.setItem("u_htmleditor", document.getElementById('editorText').value);
        quill.root.innerHTML = document.getElementById('editorText').value;
        $window.localStorage.setItem("u_contents", quill.root.innerHTML);
        $scope.blg.contents = quill.root.innerHTML;
    }

    function getCacheData() {
        if ($window.localStorage.getItem("u_url"))
            $scope.blg.url = $window.localStorage.getItem("u_url");
        if ($window.localStorage.getItem("u_title"))
            $scope.blg.title = $window.localStorage.getItem("u_title");
        if ($window.localStorage.getItem("u_metatitle"))
            $scope.blg.metatitle = $window.localStorage.getItem("u_metatitle");
        if ($window.localStorage.getItem("u_metadescription"))
            $scope.blg.metadescription = $window.localStorage.getItem("u_metadescription");
        if ($window.localStorage.getItem("u_metakeywords"))
            $scope.blg.metakeywords = $window.localStorage.getItem("u_metakeywords");
        if ($window.localStorage.getItem("u_contents")) {
            quill.root.innerHTML = $window.localStorage.getItem("u_contents");
            $scope.blg.contents = $window.localStorage.getItem("u_contents");
        }
        if ($window.localStorage.getItem("u_htmleditor"))
            document.getElementById('editorText').value = $window.localStorage.getItem("u_htmleditor")
    }
    getCacheData();


    $scope.editorSourceChange = function () {
        if ($scope.isHTMLEdit == false) {
            $scope.isHTMLEdit = true;
            document.getElementById('editorText').value = quill.root.innerHTML;
            angular.element("#editor").css("display", "none");
            $scope.changeEditor = "Switch to Editor";

        } else {
            $scope.isHTMLEdit = false;
            quill.root.innerHTML = document.getElementById('editorText').value;
            angular.element("#editor").css("display", "block");
            $scope.changeEditor = "Switch to Source Code";

        }
        console.log($scope.isHTMLEdit);
    }

    $scope.previewBlog = function () {

        console.log("Preview...");

        //$rootScope.$broadcast('preview-started', blog[0]);

        //customService.setObject({ "propX": "propX" }, customService.foo);
        // previewService.setObject({ "Hello": "hello2" }, previewService.foo);

        previewService.clearObject();
        previewService.setObject({
                title: $scope.blg.title,
                metatitle: $scope.blg.metatitle,
                metadescription: $scope.blg.metadescription,
                metakeywords: $scope.blg.metakeywords,
                contents: quill.root.innerHTML
        }, previewService.foo);

        //alert("OBJ: " + JSON.stringify(previewService.getObject()));

        $location.path('/blog/preview');
        // $window.open("/blog/preview", '_blank'); // in new tab
    }



    $scope.updateBlog = function () {
       // alert("UPDATE!");

        $scope.blg.contents = $scope.blg.contents.replace(/"/g, "\'");
        $scope.blg.keywords = $scope.blg.metakeywords;

        console.log("BLOG CONTENT: " + JSON.stringify($scope.blg));


        if (!validation()) return false;

        $http.put('/api/Blog/UpdateBlog', $scope.blg)
            .success(function (data) {
                if (data[0].C_ResultType == "Success") {
                    $scope.new_url = $scope.BASE_URL + "/" + $scope.blg.url;
                    $scope.isSuccess = true;
                    $window.localStorage.removeItem("u_url");
                    $window.localStorage.removeItem("u_title");
                    $window.localStorage.removeItem("u_metatitle");
                    $window.localStorage.removeItem("u_metadescription");
                    $window.localStorage.removeItem("u_metakeywords");
                    $window.localStorage.removeItem("u_contents");
                    $window.localStorage.removeItem("u_htmleditor");
                    $window.localStorage.removeItem("u_update_existing")
                   // $window.location.reload();
                } else {
                    alert("Ops! There is something wrong. Please try again later.")
                }
            })
        .error(function (err) {
            alert("Ops! There is something wrong with server. Please try again later.")
        });

    }

    function validation() {
        $scope.warning = [];

        if (!$scope.blg.url || !$scope.blg.title || !$scope.blg.metatitle || !$scope.blg.metadescription || !$scope.blg.metakeywords || !$scope.blg.contents) {
            if (!$scope.blg.url) {
                $scope.warning.push({ msg: "URL is blank!" });
            }
            if (!$scope.blg.title) {
                $scope.warning.push({ msg: "There is no title!" });
            }

            if (!$scope.blg.metatitle) {
                $scope.warning.push({ msg: "There is no meta title!" });
            }
            if (!$scope.blg.metadescription) {
                $scope.warning.push({ msg: "There is no meta description!" });
            }
            if (!$scope.blg.metakeywords) {
                $scope.warning.push({ msg: "There is no meta keywords!" });
            }
            if (!$scope.blg.contents) {
                $scope.warning.push({ msg: "Your contents can't be blank!" });
            }
            $scope.isWarning = true;
            return false;

        } else {
            $scope.warning = [];
            $scope.isWarning = false;

            return true;
        }

    }

    ///alert(quill.root.innerHTML)


   
});